/**
 * @author benny.zheng
 * @data 2016-06-06
 * @description 本文件用于方便复制粘贴UI模块之用，请更新这里的说明
 *              另外，考虑到一般是放在js/src/pages/page-name/main.js，因此使用../../
 *              如果不是这个目录，请更改成正确的相对路径
 */
//----------------require--------------

var viewport = require("mlib/dom/viewport"); // viewport
var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析


var when = require("mlib/util/when");
var ajax = require("mlib/io/ajax");
var lazyload = require("mlib/dom/lazyload");
var closest = require("mlib/dom/closest");
var touch = require("mlib/evt/touch");

var round = require("../plugin/util/round");
var date = require("../plugin/util/date");
var extend = require("../plugin/util/extend");
var animationEnd = require("../plugin/animation/animationEnd");
var quantity = require("../plugin/util/up-down");
var disableScroll = require("../plugin/util/disable-scroll");
var currency = require("../plugin/util/currency");
var Validator = require("../plugin/util/validator");
var array_sum = require("../plugin/array/array-sum");

var weuiDialog = require("../layer/weuidialog");
var Dialog = require("../layer/dialog");
var Alert = require("../layer/weuialert");


var layerRender = require("./layer.ejs");
var couponRender = require("./coupon.ejs");




     

module.exports = function(node, opts) {
    //-----------声明模块全局变量-------------
    var nodeList = null; // 存储所有关键节点
    var that = base();
    var data = null;
	
	var m_quantity = null;
	var m_dialog = null;
	var weui_dialog = null;
	var m_total_price = 0; // 商品总金额
	var m_pay_price = 0; // 商品实际支付金额
	var m_coupon_price = 0; // 商品优惠金额
	var m_couponobj = null;// 记录当前选中的优惠券对象
	var store_coupon = []; // 存储所有优惠券	
	var store_couponids = []; // 存储所有优惠券关联
	var cur_coupon = null; // 记录当前选中的优惠券

    var couponNodes = null; 
	var exprestr = null;
	var expreResult = null;
	var single_list = null; 
	var needidcard =null;
	var isPassed =null;
	var m_validator =null;


	var m_couponlist = null;	
	var v = null;
	var m_submit_content = null;
	var m_list = null;
	var m_layerH = null;
	var m_couponodes = null;
	var node_h = [];
	var list_h = [];
	var m_body = null;
    var fc_nodes = null; //满减优惠券节点	
	
	
    //-------------事件响应声明---------------
    var evtFuncs = {
		disableScroll:function(e){
			e.preventDefault();
			e.stopPropagation();
		},
		 validatorForm:function(evt){
			 m_validator.validate({type:evt.type,node:evt.target});
		 },
		bindQ:function(result){ // 点击数量加减更新商品总金额                  
			 var obj=result.data,
				 input=obj.input,
				 theprice = parseFloat(input.dataset.price),
				 theval =input.value;

				 m_total_price = parseInt(theval) * parseFloat(theprice);
				custFuncs.updatePrice();	
		},
		bindDialog:function(){			
					m_dialog = Dialog({
						title:"订单填写",
						shadeClose:false,
						lockScroll:false,
						content:m_submit_content,
						operates:[{name:"pay",cls:"full-btn",text:'<span>立即支付</span> <span id="sonnPayprice" node-name="sonnPayprice">&yen;'+currency(m_total_price)+'</span>',fn:function(){
							evtFuncs.validatorForm({type:null,node:null});
							if(isPassed){	

								if(that.isLock()) {
									return;
								}
								that.lock();  
								var paramdata = {};
								paramdata["ocid"] = data.ocid;								
								paramdata["tid"] = data.tid;								
								paramdata["tcid"] = data.tcid;								
								paramdata["date"] =data.date;
								paramdata["msg"] =data.msg;
								paramdata["status"]  = data.status;
								paramdata["week"] =data.week;
								single_list["number"] = couponNodes.quantity.value;
                                paramdata["list"] = JSON.stringify([single_list]);	
								if(cur_coupon){		
									m_couponobj = store_coupon[store_couponids.indexOf(cur_coupon)];
									paramdata["card"] = JSON.stringify([{"cardid":m_couponobj.cardid,"cardcode":m_couponobj.code.codeId,"couponprice":currency(m_coupon_price),"coupontitle":m_couponobj.title}]);	
								}else{
									paramdata["card"] = JSON.stringify([]);
								}	
								paramdata["mobile"] = couponNodes.mobile.value;
								paramdata["totalprice"] =currency(m_total_price);

								if(needidcard){
									paramdata["idcard"] =couponNodes.idcard.value||"";
								}else{
									paramdata["idcard"] = "";
								}

								ajax({
									url: "index.php?r=scheduled/order&ocid="+ data.ocid,
									data: paramdata,
									method: "post",
									onSuccess: function(result) {	
										that.unLock();		

										
										if(result.status==1){
											var baseurl = '/index.php?r=scheduled/pay&orderid='+result.data.orderNo+'&ocid='+data.ocid;
												if(m_pay_price==0 && cur_coupon){
													location.href=baseurl+'&type=WECHAT_CARD';
												}else{
													location.href=baseurl+'&type=WECHAT_JS';
												}
										}else{
											Alert(result.msg);
										} 

									},
									onError: function(xmlHttp) {
										that.unLock();
									}
								});
							}
						}}]
					})
					m_dialog.bind("aftershow",function(layer){
						nodeList.ticketlist.addEventListener('touchmove', evtFuncs.disableScroll, false);
						couponNodes = layer.data.nodeList;
						m_list = couponNodes.inner;
						
						evtFuncs.addBind();
				   });
				   m_dialog.bind("afterhide",function(){
					  // disableScroll.off(nodeList.ticketlist);

					  nodeList.ticketlist.removeEventListener('touchmove', evtFuncs.disableScroll, false);
					  m_body.style.overflow = 'auto';
				   });
				   
				   m_dialog.init();
				   
				   m_validator = null;
					var inforules =[{
						//name 字段
						name: 'mobile',
						display:"请输入手机号码|手机号码不正确",
						// 验证条件
						rules: 'required|is_phone'
					}];
					if(needidcard){
						inforules.push({
							//name 字段
							name: 'idcard',
							display:"请输入身份证|身份证错误",
							// 验证条件
							rules: 'required|is_idcard'
						});
					}

					m_validator = new Validator('orderForm',inforules,function(obj,evt){
						isPassed =false;
						if(obj.errors.length>0){
							var firstObj = null;
							 obj.errors.forEach(function(item,index){
								 var itemEl = item.element;
								 if(evt.type==null && index==0){
									 firstObj = item;
								 }else{
									 if(evt.node==itemEl){
										 firstObj = item;
									 }
								 }

								 
								 if(itemEl.classList.contains("error")){
									 itemEl.classList.remove("error","shake");
								 }
								 
							 });
							 
							// 判断是否错误
							switch(evt.type){
								case "input":
									if(firstObj){
										if(firstObj.rule=="is_phone" && firstObj.element.value.length>11){
											firstObj.element.classList.add("error");
										}else if(firstObj.rule=="is_idcard" && firstObj.element.value.length>18){
											firstObj.element.classList.add("error");
										}
									}                        
									break; 			
								case "blur":
								case null:
									if(firstObj){
										var cls = firstObj.rule =="required" ? "empty" : "error";
											firstObj.element.classList.add(cls,"shake");
											animationEnd(firstObj.element, 'AnimationEnd', function () {
												firstObj.element.classList.remove("shake");
											}, false);
									}
									break; 	
								
							}
							return ;
							 
						}
						isPassed =true;
					});
		},
		showTicket:function(evt){
			      //  disableScroll.on(nodeList.ticketlist);
				  m_body.style.overflow = 'hidden';
				  single_list = null;
				  cur_coupon = null;
				var target = closest(evt.target,"button.btn-white",true),
					strbtnObj = JSON.stringify(target.dataset),
					params = JSON.parse(strbtnObj);

					single_list = extend({},params);

					m_total_price = params.min * params.price;	
					
					needidcard = Boolean(parseInt(params.idcard));				
					params["needIdCard"] = needidcard;
					params["ocid"] = data.ocid;
					params["hascoupon"] = data.subscribe==1 ? true : false;
					
					m_submit_content=layerRender(params);					
		
					evtFuncs.bindDialog();
					if(data.subscribe==1){
						custFuncs.getCoupon(params.apiurl).then(function(result){     
							if(cur_coupon){
								custFuncs.updatePrice();
							}
						});
					}
		},
		preferential:function(evt){			
			var checkedbox=closest(evt.target,".coupon-item",true);
				if(checkedbox.classList.contains("disabled")){
                     return;
				}
				m_couponodes.forEach(function(item){
					if(item==checkedbox){
						item.classList.toggle("coupon-item-checked");						
						if(item.classList.contains("coupon-item-checked")){				
							cur_coupon = item.dataset.cardid;							
						}else{
							cur_coupon = null;
						}						
						custFuncs.updatePrice();
					}else{
						item.classList.remove("coupon-item-checked");	
					}
				});	
		},
		showAll:function(e){
			var morelem = closest(e.target,".loadmore",true);
			morelem.parentElement.removeChild(morelem);

			m_couponodes.forEach(function(item){
				item.classList.remove("hide");
			});	
		},
		addBind:function(){
			m_couponlist = m_list.querySelector(".coupon-list");			
			touch.on(m_list, 'tap', ".coupon-item", evtFuncs.preferential);
			touch.on(m_list, 'tap', ".loadmore", evtFuncs.showAll);
			couponNodes.mobile.addEventListener("blur", evtFuncs.validatorForm);			
			couponNodes.mobile.addEventListener("input", evtFuncs.validatorForm, false);
			if(needidcard){
				couponNodes.idcard.addEventListener("blur", evtFuncs.validatorForm);
				couponNodes.idcard.addEventListener("input", evtFuncs.validatorForm);
			}
		},
		bookNotice:function(evt){
				var target = closest(evt.target,"span.order-notice",true),id=target.dataset.id;
				if(that.isLock()) {
					return;
				}
				that.lock();
				ajax({ 
					url: "/index.php?r=goods/goodsdetail&id="+ id+"&ocid="+ data.ocid,
					onSuccess: function(result) {
						that.unLock();
						weui_dialog = null;
						weui_dialog = weuiDialog({	
						//	shadeClose:false,
							lockScroll:false,						
							title:"预定须知",		
							content:result.bookingnotice		
						});		
						weui_dialog.bind("aftershow",function(layer){
							var dnodes = layer.data.nodeList;
							dnodes.content.parentElement.style.height = document.documentElement.clientHeight/2 + "px";
					   });
					   weui_dialog.init();
					},
					onError: function(xmlHttp) {
						that.unLock();
					}
				});
		}
	}

    //-------------子模块实例化---------------
    var initMod = function() {
		
		m_body = document.body;
		m_quantity = quantity(m_body,{});
		var 
		bdH = nodeList.ticketwindow.clientHeight,
		tkTop = nodeList.ticketlist.getBoundingClientRect().top,
		tkH = nodeList.ticketlist.scrollHeight,
		ftH = nodeList.footer.clientHeight,
		pkH = nodeList.polka.clientHeight*2,
		restH  =  bdH-(tkTop+pkH+ftH),
		isSetH = restH <= tkH;
		if(data.rows.length >0 && isSetH){
			nodeList.ticketlist.style.height =Math.round(restH) + "px";
		}else{
			nodeList.ticketwindow.classList.add('limit-ticket');
		}
    }

    //-------------绑定事件------------------
    var bindEvents = function() {
			touch.on(nodeList.ticketlist, 'tap', "button.btn-white", evtFuncs.showTicket);
			touch.on(nodeList.ticketlist, 'tap', "span.order-notice", evtFuncs.bookNotice);
		    m_quantity.bind("inputChange", evtFuncs.bindQ);
	}

    //-------------自定义函数----------------
    var custFuncs = {
		   updateCoupon:function(money){
		   		fc_nodes  && fc_nodes.forEach(function(item,index){
                    if(m_total_price<parseFloat(item.dataset.money)){
                         item.classList.add("disabled");
                    }else{
                    	item.classList.remove("disabled");
                    }
		   		});
		   },
		   updateCouponNodes:function(){
		   	    fc_nodes = [];
		   		m_couponodes = [].slice.call(m_list.querySelectorAll(".coupon-item"));
		   		m_couponodes.forEach(function(item,index){
		   			if(item.hasAttribute("data-money")){
                       fc_nodes.push(item); 
		   			}
		   		});
		   },
           getCoupon:function(apiurl){		    

				var defer = when.defer();
				ajax({ 
					url: apiurl,
					data: {}, 
					method: "post",
					onSuccess: function(result) {
					if(result.status>0){
					  var coupondata = result.data;
					  that.unLock();	
					  m_couponlist.innerHTML = ''; 
						   if(coupondata.length>0){
							   coupondata.forEach(function(item,index){
								   if(index==0){
									   	if(item.money==0){
										   cur_coupon = ""+item.cardId;
									   	}else if(m_total_price>round(item.money)){
											cur_coupon = ""+item.cardId;
									   	}
								   }
								   item.reckon = "-" + round(item.reduceCost);
								   item.amount = round(item.reduceCost);
								   store_coupon.push(item);
								   store_couponids.push(""+item.cardId);							   
							   });	

							  m_couponlist.insertAdjacentHTML("beforeend",couponRender({"couponlist":coupondata}));
							  custFuncs.updateCouponNodes();	

								if(cur_coupon){
									m_couponodes[0].classList.add("coupon-item-checked");
								}				
						   }else{
							   couponNodes.coupontips.innerHTML = '暂无可用券';
						   }
						   custFuncs.updatePrice();	
						}
					    defer.resolve({});
					},
					onError: function(xmlHttp) {
						 that.unLock();
					}
				});
						

				return defer.promise; // 注意不管如何，函数在return时一定要返回这个对象
		   },
		   updatePrice:function(){							
				if(cur_coupon){
					m_couponobj = store_coupon[store_couponids.indexOf(cur_coupon)];
					var exprestr = m_total_price+m_couponobj.reckon;
						expreResult = eval(exprestr);
						m_pay_price=expreResult; // 支付金额
						m_coupon_price = m_total_price-expreResult; // 优惠金额(优惠了多少)
				}else{
					m_pay_price = m_total_price;
					m_coupon_price = 0;
				}
	
                if(m_pay_price<0){
					m_pay_price = 0.00;
				}else{
					m_pay_price = currency(m_pay_price,2);
				}
				custFuncs.updateCoupon();
			   couponNodes.sonnPayprice.innerHTML="&yen;"+m_pay_price;
		   }
    };

    //-------------一切从这开始--------------
    var init = function(_data) {

        data = _data;

        // 找到所有带有node-name的节点
        nodeList = parseModule(node);
        // 子模块实例化
        initMod();
        // 绑定事件
        bindEvents();

    }

    //---------------暴露API----------------
    that.init = init;

    return that;
};